#include <iostream>

#include "serialization.hpp"
#include "Sock.hpp"

Respond Compute(const Request &reqt)
{
    Respond resd(0, 0);
    switch (reqt._op)
    {
    case '+':
        resd._result = reqt._x + reqt._y;
        break;
    case '-':
        resd._result = reqt._x - reqt._y;
        break;
    case '*':
        resd._result = reqt._x * reqt._y;
        break;
    case '/':
        if (reqt._y == 0)
            resd._code = 1;
        else
            resd._result = reqt._x / reqt._y;
        break;
    case '%':
        if (reqt._y == 0)
            resd._code = 2;
        else
            resd._result = reqt._x % reqt._y;
        break;
    default:
        resd._code = 3;
        break;
    }

    return resd;
}

void Calculator(int _serversockfd)
{
    while (true)
    {
        // 执行任务
        //  1. 接受客户端发来的信息
        Sock sock;
        std::string buffer;
        sock.Revc(_serversockfd, buffer);

        // 2. 处理信息
        Request rqt;
        rqt.Deserialization(buffer);
        Respond rpd = Compute(rqt);
        std::string res = rpd.Serialization();

        // 3. 将信息写回到客户端
        sock.Send(_serversockfd, res);
    }
}